//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web;
using System.Xml;

namespace CommunityServer.Components
{
	/// <summary>
	/// Rules CS enforces/validates when a user enters the site
	/// </summary>
	public class CSMembershipRulesModule : ICSModule
	{
		public CSMembershipRulesModule()
		{
		}

		#region ICSModule Members

		public void Init(CSApplication csa, XmlNode node)
		{
			csa.UserKnown +=new CSUserEventHandler(csa_UserKnown);
			csa.AuthorizePost +=new CSUserEventHandler(csa_AuthorizePost);
		}

		#endregion

		/// <summary>
		/// Once a user is known, we can check the Force login and their banned status
		/// </summary>
		private void csa_UserKnown(User user, CSEventArgs e)
		{
			if (user.ForceLogin) 
			{
				Users.ToggleForceLogin(user);
				HttpContext.Current.Response.Redirect(Globals.GetSiteUrls().Logout, true);
			}

			if (user.IsBanned && DateTime.Now > user.BannedUntil) 
			{
				// Update to back to datastore
				//
				user.AccountStatus = UserAccountStatus.Approved;
				user.BannedUntil = DateTime.Now;
				Users.UpdateUser(user);
			}



		}

		/// <summary>
		/// This event wil be raised by any control which access a post. User's in CS my view the site
		/// even when they are banned. This verifies banned users can not add new posts
		/// </summary>
		private void csa_AuthorizePost(User user, CSEventArgs e)
		{
			if(user.IsBanned)
			{
				if(DateTime.Now <= user.BannedUntil) 
				{
					HttpContext.Current.Response.Redirect(Globals.GetSiteUrls().UserBanned, true);   
				}
			}
		}
	}
}
